package com.example.musicgui.client;

import javax.sound.sampled.*;
import java.io.*;
import java.net.Socket;

public class AudioClient {
    private Socket socket = null;
    private File audioFile = null;
    private SourceDataLine sdl;
    private int musicBytes;
    public boolean isStatus;
    private AudioInputStream as;

    public AudioClient() {
        try {
            socket = new Socket(Client.HOST, Client.PORT_TWO); // 连接到服务器
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.isStatus = false;
    }

    private void getMusic(String url) throws IOException {
        // 发送音频文件路径给服务器
        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
        writer.println(url);
        // 接收服务器传来的音频文件
        this.audioFile = new File("audio.wav");
        System.out.println("接收音乐");
        FileOutputStream fos = new FileOutputStream(audioFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        InputStream is = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        bos.close();
        socketClose();
    }

    public void audio(String url) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
        getMusic(url);
        // 播放接收到的音频文件
        as = AudioSystem.getAudioInputStream(this.audioFile);
        AudioFormat format = as.getFormat();
        this.sdl = AudioSystem.getSourceDataLine(format);
        this.sdl.open(format);
        this.sdl.start();
        musicBytes = 0;
        byte[] abData = new byte[512];

        while (musicBytes != -1) {
            if (!isStatus) {
                this.musicBytes = as.read(abData, 0, abData.length);
                if (musicBytes >= 0) {
                    this.sdl.write(abData, 0, musicBytes);
                }
            } else {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("播放完成");
        close();
    }

    public void close() {
        this.sdl.drain();
        this.sdl.close();
    }
    public void socketClose() throws IOException {
        socket.close();
    }
}

